package rsj.api.user;

import com.rlyy.aibase.db.Dbink;
import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import common.util.Assert;
import common.util.BoxUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rsj.dao.UserInfoDao;
import rsj.db.PostgresqlConn;
import rsj.service.UserInfoService;
import rsj.utils.RedisUtils;

import java.sql.Connection;
import java.util.Objects;

/**
 * @author yuanqinglong
 * @since 2020/10/14 16:38
 */
@RestController
public class UserResetPwd extends BaseLink {
    private static final UserInfoDao INFO_DAO = UserInfoDao.getInstance();

    @Override
    @RequestMapping(value = "rsj_sso_sys_resetPwd")
    public Box executeLink(Box box) {
        MapNode data = box.getMapNode("data");
        String tid = box.getNode("$tid");
        Connection connection = PostgresqlConn.getConnection();
        try {
            String userUname = data.getValue("user_uname");
            Assert.isNotBlank(userUname, "账号为空");
            MapNode userByUserName = INFO_DAO.getUserByUserName(connection, userUname);
            if (userByUserName.size() == 0 || !Objects.equals(userUname, userByUserName.getValue("User_Uname"))) {
                return BoxUtil.errorBox(box, "用户名不存在");
            }

            String userEmail = data.getValue("user_email");
            Assert.isNotBlank(userEmail, "邮箱为空");
            String emailValidCod = data.getValue("email_valid_cod");
            Assert.isNotBlank(emailValidCod, "验证码为空");
            String newUserPwd = data.getValue("new_user_pwd");
            Assert.isNotBlank(newUserPwd, "新密码为空");
            String sms = String.format("rsj:%s:%s", "01", userEmail);
//        String vcode = JedisUtil.get(sms, tid);
            String vcode = RedisUtils.getString(sms);
            if (!Objects.equals(vcode, emailValidCod)) {
                return BoxUtil.errorBox(box, "验证码错误或已失效");
            }
            INFO_DAO.updatePassword(connection, userUname,  UserInfoService.stringToMD5(newUserPwd));
            String key = "rsj|login|userId|" + userByUserName.getValue("user_id");
//            JedisUtil.del(sms, tid);
//            JedisUtil.del(key, tid);
            RedisUtils.del(sms,key);
        } finally {
            Dbink.close(connection);
        }
        return BoxUtil.successBox(box, "修改成功");
    }


}
